package com.jishucai;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @author admin
 */
public class SomeServer {
    public static void main(String[] args) throws InterruptedException {

        // 用于启动channel
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 用于处理客户端连接请求，将请求发送给childGroup中的eventLoop
        NioEventLoopGroup parentGroup = new NioEventLoopGroup();

        // 用于处理客户端请求,
        NioEventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            serverBootstrap
                    // 指定eventLoop
                    .group(parentGroup, childGroup)
                    // 指定使用nio进行通信
                    .channel(NioServerSocketChannel.class)
                    // 执行处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();

                            //HttpServerCodec 放入到 pipeline
                            channelPipeline.addLast(new HttpServerCodec());
                            // 将自定义的处理器放到最后面
                            channelPipeline.addLast(new SomeServerHandler());
                        }
                    });
            // bind()方法执行是异步的
            // sync（）方法保证后续代码由异步变成了同步
            ChannelFuture bind = serverBootstrap.bind(8888).sync();
            System.out.println("服务器启动成功，端口是8888");

            bind.channel().closeFuture().sync();
        }  finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }

    }
}
